import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'dart:math';
import 'models.dart';

class ApartmentGamePage extends StatefulWidget {
  const ApartmentGamePage({super.key});

  @override
  State<ApartmentGamePage> createState() => _ApartmentGamePageState();
}

class _ApartmentGamePageState extends State<ApartmentGamePage>
    with TickerProviderStateMixin {
  // 游戏状态
  bool isGameRunning = true;
  
  // 屏幕尺寸
  double screenWidth = 0;
  double screenHeight = 0;
  
  // 游戏数据
  List<Floor> floors = [];
  Player player = Player(x: 0, y: 0);
  Room? playerRoom;
  
  // 游戏常量
  final double floorHeight = 120; // 每层楼的高度
  final double roomWidth = 100; // 每个房间的宽度
  final double corridorWidth = 40; // 走廊宽度
  final int roomsPerFloor = 6; // 每层房间数
  
  // 玩家控制
  double moveSpeed = 3.0;
  bool isMovingLeft = false;
  bool isMovingRight = false;
  bool isMovingUp = false;
  bool isMovingDown = false;
  
  // 动画控制器
  late AnimationController gameLoopController;
  
  // 随机数生成器
  final Random random = Random();
  
  @override
  void initState() {
    super.initState();
    
    // 初始化游戏循环
    gameLoopController = AnimationController(
      vsync: this,
      duration: const Duration(milliseconds: 16), // 约60FPS
    );
    
    gameLoopController.addListener(() {
      if (isGameRunning) {
        updateGame();
      }
    });
    
    gameLoopController.repeat();
    
    // 延迟初始化，等待布局完成
    WidgetsBinding.instance.addPostFrameCallback((_) {
      initializeGame();
    });
  }
  
  @override
  void dispose() {
    gameLoopController.dispose();
    super.dispose();
  }
  
  void initializeGame() {
    setState(() {
      screenWidth = MediaQuery.of(context).size.width;
      screenHeight = MediaQuery.of(context).size.height;
      
      // 生成公寓结构
      generateApartment();
      
      // 初始化玩家位置（301房间）
      if (playerRoom != null) {
        player.x = playerRoom!.x + playerRoom!.width / 2 - player.width / 2;
        player.y = playerRoom!.y + playerRoom!.height / 2 - player.height / 2;
      }
    });
  }
  
  /// 生成公寓结构（7层楼）
  void generateApartment() {
    floors.clear();
    
    for (int floor = 1; floor <= 7; floor++) {
      List<Room> rooms = [];
      
      // 计算该楼层在屏幕上的Y位置（从下往上）
      double floorY = screenHeight - (floor * floorHeight) - 20;
      
      // 生成该楼层的房间
      for (int i = 0; i < roomsPerFloor; i++) {
        String roomNumber = '${floor}0${i + 1}';
        double roomX = 50 + i * (roomWidth + corridorWidth);
        double roomY = floorY;
        
        bool isPlayerRoom = (floor == 3 && i == 0); // 301房间是玩家房间
        
        Room room = Room(
          roomNumber: roomNumber,
          floorNumber: floor,
          roomIndex: i,
          x: roomX,
          y: roomY,
          width: roomWidth,
          height: floorHeight - 20,
          isPlayerRoom: isPlayerRoom,
        );
        
        // 如果不是玩家房间，创建NPC
        if (!isPlayerRoom) {
          room.npc = createNPCForRoom(room);
        } else {
          playerRoom = room;
        }
        
        rooms.add(room);
      }
      
      floors.add(Floor(
        floorNumber: floor,
        rooms: rooms,
      ));
    }
  }
  
  /// 为房间创建NPC
  NPC createNPCForRoom(Room room) {
    // 随机生成NPC名字
    List<String> names = ['张三', '李四', '王五', '赵六', '钱七', '孙八', 
                          '周九', '吴十', '郑一', '王二', '陈三', '刘四'];
    String name = names[random.nextInt(names.length)];
    
    // 随机生成NPC颜色
    List<Color> colors = [
      Colors.blue,
      Colors.green,
      Colors.orange,
      Colors.purple,
      Colors.pink,
      Colors.teal,
      Colors.amber,
      Colors.cyan,
    ];
    Color npcColor = colors[random.nextInt(colors.length)];
    
    // 生成NPC的活动轨迹（在房间内移动）
    List<ActivityPoint> activityPoints = generateActivityPoints(room);
    
    // NPC初始位置在房间中心
    double npcX = room.x + room.width / 2;
    double npcY = room.y + room.height / 2;
    
    return NPC(
      name: name,
      roomNumber: room.roomNumber,
      color: npcColor,
      x: npcX,
      y: npcY,
      activityPoints: activityPoints,
      moveSpeed: 0.5 + random.nextDouble() * 1.0, // 随机移动速度
    );
  }
  
  /// 生成NPC的活动轨迹点
  List<ActivityPoint> generateActivityPoints(Room room) {
    List<ActivityPoint> points = [];
    
    // 生成3-5个活动点
    int pointCount = 3 + random.nextInt(3);
    
    for (int i = 0; i < pointCount; i++) {
      // 在房间内随机生成活动点（留出边距）
      double margin = 20;
      double pointX = room.x + margin + random.nextDouble() * (room.width - margin * 2);
      double pointY = room.y + margin + random.nextDouble() * (room.height - margin * 2);
      
      // 随机等待时间（1-5秒）
      double waitTime = 1.0 + random.nextDouble() * 4.0;
      
      points.add(ActivityPoint(
        x: pointX,
        y: pointY,
        waitTime: waitTime,
        description: _getRandomActivity(),
      ));
    }
    
    return points;
  }
  
  /// 获取随机活动描述
  String _getRandomActivity() {
    List<String> activities = [
      '休息',
      '走动',
      '思考',
      '观察',
      '整理',
      '阅读',
    ];
    return activities[random.nextInt(activities.length)];
  }
  
  /// 更新游戏逻辑
  void updateGame() {
    if (!mounted) return;
    
    setState(() {
      // 更新玩家位置
      if (isMovingLeft) {
        player.velocityX = -moveSpeed;
        player.isFacingRight = false;
      } else if (isMovingRight) {
        player.velocityX = moveSpeed;
        player.isFacingRight = true;
      } else {
        player.velocityX = 0;
      }
      
      if (isMovingUp) {
        player.velocityY = -moveSpeed;
      } else if (isMovingDown) {
        player.velocityY = moveSpeed;
      } else {
        player.velocityY = 0;
      }
      
      player.x += player.velocityX;
      player.y += player.velocityY;
      
      // 边界检查
      if (player.x < 0) player.x = 0;
      if (player.x + player.width > screenWidth) {
        player.x = screenWidth - player.width;
      }
      if (player.y < 0) player.y = 0;
      if (player.y + player.height > screenHeight) {
        player.y = screenHeight - player.height;
      }
      
      // 更新所有NPC
      for (Floor floor in floors) {
        for (Room room in floor.rooms) {
          if (room.npc != null) {
            room.npc!.update();
          }
        }
      }
    });
  }
  
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.grey[200],
      body: Stack(
        children: [
          // 游戏渲染区域
          CustomPaint(
            size: Size.infinite,
            painter: ApartmentGamePainter(
              floors: floors,
              player: player,
            ),
          ),
          
          // 控制按钮
          Positioned(
            bottom: 20,
            left: 20,
            child: _buildControlButtons(),
          ),
          
          // 信息显示
          Positioned(
            top: 20,
            left: 20,
            child: Container(
              padding: const EdgeInsets.all(15),
              decoration: BoxDecoration(
                color: Colors.black54,
                borderRadius: BorderRadius.circular(10),
              ),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    '公寓游戏',
                    style: const TextStyle(
                      color: Colors.white,
                      fontSize: 18,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                  SizedBox(height: 5),
                  Text(
                    '玩家房间: 301',
                    style: const TextStyle(color: Colors.white, fontSize: 14),
                  ),
                  Text(
                    '当前楼层: ${player.currentFloor}',
                    style: const TextStyle(color: Colors.white, fontSize: 14),
                  ),
                ],
              ),
            ),
          ),
          
          // 返回按钮
          Positioned(
            top: 20,
            right: 20,
            child: GestureDetector(
              onTap: () => Navigator.pop(context),
              child: Container(
                padding: const EdgeInsets.all(10),
                decoration: BoxDecoration(
                  color: Colors.red.withOpacity(0.8),
                  borderRadius: BorderRadius.circular(10),
                ),
                child: const Icon(
                  Icons.arrow_back,
                  color: Colors.white,
                  size: 24,
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }
  
  /// 构建控制按钮
  Widget _buildControlButtons() {
    return Container(
      width: 200,
      height: 200,
      child: Stack(
        children: [
          // 方向键背景
          Positioned(
            left: 50,
            top: 50,
            child: Container(
              width: 100,
              height: 100,
              decoration: BoxDecoration(
                color: Colors.black26,
                borderRadius: BorderRadius.circular(10),
              ),
            ),
          ),
          // 上
          Positioned(
            left: 70,
            top: 30,
            child: GestureDetector(
              onTapDown: (_) => setState(() => isMovingUp = true),
              onTapUp: (_) => setState(() => isMovingUp = false),
              onTapCancel: () => setState(() => isMovingUp = false),
              child: Container(
                width: 60,
                height: 40,
                decoration: BoxDecoration(
                  color: Colors.blue.withOpacity(0.7),
                  borderRadius: BorderRadius.circular(5),
                ),
                child: Icon(Icons.arrow_upward, color: Colors.white),
              ),
            ),
          ),
          // 下
          Positioned(
            left: 70,
            top: 130,
            child: GestureDetector(
              onTapDown: (_) => setState(() => isMovingDown = true),
              onTapUp: (_) => setState(() => isMovingDown = false),
              onTapCancel: () => setState(() => isMovingDown = false),
              child: Container(
                width: 60,
                height: 40,
                decoration: BoxDecoration(
                  color: Colors.blue.withOpacity(0.7),
                  borderRadius: BorderRadius.circular(5),
                ),
                child: Icon(Icons.arrow_downward, color: Colors.white),
              ),
            ),
          ),
          // 左
          Positioned(
            left: 20,
            top: 80,
            child: GestureDetector(
              onTapDown: (_) => setState(() => isMovingLeft = true),
              onTapUp: (_) => setState(() => isMovingLeft = false),
              onTapCancel: () => setState(() => isMovingLeft = false),
              child: Container(
                width: 40,
                height: 60,
                decoration: BoxDecoration(
                  color: Colors.blue.withOpacity(0.7),
                  borderRadius: BorderRadius.circular(5),
                ),
                child: Icon(Icons.arrow_back, color: Colors.white),
              ),
            ),
          ),
          // 右
          Positioned(
            left: 140,
            top: 80,
            child: GestureDetector(
              onTapDown: (_) => setState(() => isMovingRight = true),
              onTapUp: (_) => setState(() => isMovingRight = false),
              onTapCancel: () => setState(() => isMovingRight = false),
              child: Container(
                width: 40,
                height: 60,
                decoration: BoxDecoration(
                  color: Colors.blue.withOpacity(0.7),
                  borderRadius: BorderRadius.circular(5),
                ),
                child: Icon(Icons.arrow_forward, color: Colors.white),
              ),
            ),
          ),
        ],
      ),
    );
  }
}

/// 游戏渲染器
class ApartmentGamePainter extends CustomPainter {
  final List<Floor> floors;
  final Player player;
  
  ApartmentGamePainter({
    required this.floors,
    required this.player,
  });
  
  @override
  void paint(Canvas canvas, Size size) {
    // 绘制楼层和房间
    for (Floor floor in floors) {
      for (Room room in floor.rooms) {
        // 绘制房间
        final roomPaint = Paint()
          ..color = room.isPlayerRoom ? Colors.lightGreen[300]! : Colors.white
          ..style = PaintingStyle.fill
          ..strokeWidth = 2;
        
        canvas.drawRect(
          Rect.fromLTWH(room.x, room.y, room.width, room.height),
          roomPaint,
        );
        
        // 绘制房间边框
        final borderPaint = Paint()
          ..color = Colors.grey[700]!
          ..style = PaintingStyle.stroke
          ..strokeWidth = 2;
        
        canvas.drawRect(
          Rect.fromLTWH(room.x, room.y, room.width, room.height),
          borderPaint,
        );
        
        // 绘制房间号
        final textPainter = TextPainter(
          text: TextSpan(
            text: room.roomNumber,
            style: TextStyle(
              color: Colors.black,
              fontSize: 12,
              fontWeight: FontWeight.bold,
            ),
          ),
          textDirection: TextDirection.ltr,
        );
        textPainter.layout();
        textPainter.paint(
          canvas,
          Offset(room.x + 5, room.y + 5),
        );
        
        // 绘制NPC
        if (room.npc != null) {
          final npcPaint = Paint()
            ..color = room.npc!.color
            ..style = PaintingStyle.fill;
          
          canvas.drawRect(
            Rect.fromLTWH(
              room.npc!.x - room.npc!.width / 2,
              room.npc!.y - room.npc!.height / 2,
              room.npc!.width,
              room.npc!.height,
            ),
            npcPaint,
          );
          
          // 绘制NPC名字
          final npcNamePainter = TextPainter(
            text: TextSpan(
              text: room.npc!.name,
              style: TextStyle(
                color: Colors.black,
                fontSize: 10,
              ),
            ),
            textDirection: TextDirection.ltr,
          );
          npcNamePainter.layout();
          npcNamePainter.paint(
            canvas,
            Offset(
              room.npc!.x - npcNamePainter.width / 2,
              room.npc!.y - room.npc!.height / 2 - 15,
            ),
          );
          
          // 绘制NPC活动轨迹点（调试用，可选）
          if (room.npc!.activityPoints.isNotEmpty) {
            final pointPaint = Paint()
              ..color = room.npc!.color.withOpacity(0.3)
              ..style = PaintingStyle.fill;
            
            for (ActivityPoint point in room.npc!.activityPoints) {
              canvas.drawCircle(
                Offset(point.x, point.y),
                3,
                pointPaint,
              );
            }
          }
        }
      }
    }
    
    // 绘制玩家
    final playerPaint = Paint()
      ..color = Colors.red
      ..style = PaintingStyle.fill;
    
    canvas.drawRect(
      Rect.fromLTWH(player.x, player.y, player.width, player.height),
      playerPaint,
    );
    
    // 绘制玩家眼睛
    final eyePaint = Paint()
      ..color = Colors.white
      ..style = PaintingStyle.fill;
    
    if (player.isFacingRight) {
      canvas.drawCircle(
        Offset(player.x + player.width - 8, player.y + 10),
        3,
        eyePaint,
      );
    } else {
      canvas.drawCircle(
        Offset(player.x + 8, player.y + 10),
        3,
        eyePaint,
      );
    }
  }
  
  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) => true;
}


